/* vcc/robot.c 
 * 
 * This file is part of vcc. 
 * 
 * vcc is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * vcc is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with vcc. If not, see <https://www.gnu.org/licenses/>
 */ 




#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <poll.h>
#include <signal.h>

#include <klist.h>
#include <vcc/vcc.h>
#include <vcc/plugin.h>
#include <vcc/version.h>
#include <vcc/pretty.h>
#include <vcc/interfaces.h>

int becomes_daemon(void) {
	int pid, fd;

	if ((pid = fork())) 
		/* then prompt was there again */
		exit(0);

	umask(0);
	chdir("/");

	close(0);

	if (unlikely(open("/var/log/vcc.log", O_WRONLY | O_CREAT, 0644) < 0)) {
		perror("open(/var/run/vcc.log)");

		exit(1);
	}

	close(1);
	close(2);

	(void) dup(0);
	(void) dup(0);

	setsid();

	if (unlikely((fd = open("/var/run/vcc.pid", O_WRONLY | O_CREAT, 0644))) < 0) {
		perror("open(/var/run/vcc.pid)");

		exit(1);
	}

	dprintf(fd, "%d\n", getpid());
	close(fd);

	/* fd 3 is now /var/run/vcc.pid */
	printf(VCC_VERSION " started. \n");

	return 0;
}


int robot(void) {
	struct vcc_relay_header hdr;

//	becomes_daemon();

	vcc_login("robot", "robot");
	strcpy(usrname, "robot");

	insert_delayed_plugins();

	for (;;) {
		memset(&hdr, 0, sizeof(struct vcc_relay_header));
		read(fd, &hdr, sizeof(struct vcc_relay_header));

		do_new_request(&hdr);
	}

	return 0;
}


